/**
 * 计时器 UI 部分
 */

import MyTimer from './myTimer';

class TimerPanel {

  // config
  parent = null;
  zrender = null;
  zrInstance = null;
  /** @type {MyTimer} */
  timer = null;

  // UI
  t1 = null;
  t2 = null;

  // param
  showDelta = 0;

  constructor(options) {
    this.parent = options.parent;
    this.zrender = options.zrender;
    this.zrInstance = options.zrInstance;
    this.timer = options.timer;

    let {t1, t2} =
      drawInit(this.parent.width, this.parent.height, this.zrender, this.zrInstance);
    this.t1 = t1;
    this.t2 = t2;
  };

  tick() {
    if (this.timer.delta == this.showDelta) {
      return;
    }

    let text = timeText(this.timer);
    this.t1.attr({style:{text}});
    this.t2.attr({style:{text}});
    this.showDelta = this.timer.delta;
  };

  /**
   * 文字颜色: stop ? 黄色 : 蓝色
   * @param {boolean} stop
   */
  color(stop) {
    let c = stop ? 'rgb(255,242,0)' : '#0FF';
    this.t1.attr({style:{textFill:c}});
  };

  destroy() {
    // no-thing
  };
}

/**
 * 开始时画什么？ '00.0'
 * @param {number} canvasWidth 
 * @param {number} canvasHeight 
 * @param zrender 
 * @param zr 
 */
function drawInit(canvasWidth, canvasHeight, zrender, zr) {
  var t1 = new zrender.Text({
    style: {
      text: '00:0',
      textAlign: 'center',
      textVerticalAlign: 'middle',
      fontSize: 72,
      fontFamily: 'Consolas',
      textFill: '#0ff'
    },
    position: [canvasWidth / 2, canvasHeight / 2]
  });
  var t2 = new zrender.Text({
    style: {
      text: '00:0',
      textAlign: 'center',
      textVerticalAlign: 'middle',
      fontSize: 72,
      fontFamily: 'Consolas',
      textFill: '#222',
      blend: 'darken'
    },
    position: [canvasWidth / 2 + 3, canvasHeight / 2 + 3]
  });
  zr.add(t2);
  zr.add(t1);

  return {t1, t2};
}

/**
 * 返回时间文本
 * @param {MyTimer} timer
 */
function timeText(timer) {
  let delta = timer.delta;

  var text = null;
  if (timer.s < 10) {
    text = '0' + timer.s + '.' + timer.ds;
  } else {
    text = timer.s + '.' + timer.ds;
  }

  // minute
  if (delta >= 600) {
    if (timer.m < 10 && timer.delta >= 36000) {
      text = '0' + timer.m + ':' + text;
    } else {
      text = timer.m + ':' + text;
    }
  }

  // hour
  if (delta >= 36000) {
    text = timer.h + ':' + text;
  }

  return text;
};

export default TimerPanel;
